package test.fra;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class FraApp {
	private static String domainContent;
	private static final String model_prefix = "--";
	private static final String keys = "@,#,--";

	public static void main(String[] args) throws IOException {

		File domain = FraApp.loadClasspathFile("/test/fra/domain.fra");
		FraConfig config = new FraApp().preparse(domain);
		for (Model model : config.models) {
			System.out.println(model);
		}
		for (Flow flow : config.flows) {
			System.out.println(flow);
		}

	}

	/**
	 * 加载类路径下的文件
	 * 
	 * @param path
	 * @return
	 */
	public static File loadClasspathFile(String path) {
		String classpath = FraApp.class.getResource("/").getPath();
		return new File(classpath + path);
	}

	public List<Model> parseDomain(File file)
			throws UnsupportedCharsetException {
		List<Model> models = new ArrayList<Model>();
		try {
			FileReader fileReader = new FileReader(file);
			@SuppressWarnings("unchecked")
			List<String> readLines = IOUtils.readLines(fileReader);
			Model model = null;
			for (String str : readLines) {
				if (str.equals("--")) {
					throw new UnsupportedCharsetException(
							"Model name is needed!");
				}
				if (str.isEmpty() || str.equals("\n")) {
					continue;
				}
				if (str.startsWith(model_prefix)) {
					model = new Model();
					models.add(model);
					model.name = str.substring(model_prefix.length()).trim();
				} else {
					model.fields.add(str.trim());

				}
			}

		} catch (FileNotFoundException e) {
			return null;
		} catch (IOException e) {
			return null;
		}

		return models;

	}

	/**
	 * 预处理
	 * 
	 * @param file
	 * @throws IOException
	 */
	private FraConfig preparse(File file) throws IOException {
		String content = FileUtils.readFileToString(file);
		FraConfig config = new FraConfig();
		String[] parts = content.substring(1).split("#");
		for (String string : parts) {
			if (string.startsWith("model")) {
				String[] models = string.split("--");
				for (int i = 1; i < models.length; i++) {
					config.models.add(Model.from(models[i]));
				}
			}
			if (string.startsWith("flow")) {
				String[] flows = string.split("@");
				for (int i = 1; i < flows.length; i++) {
					config.flows.add(Flow.from(flows[i]));
				}
			}
		}
		return config;

	}

}
